import React, { Component } from 'react';
import { Button, Modal, Form, PageHeader, Badge, Radio, Checkbox, Row } from 'antd';
import '@/assets/css/settings';
import { BasicLayout, BasicLayoutSearch } from '../../../components/BasicLayout';
import { TableCustomize } from '../Components/TableCustomize'
import { BasicPagination, isInvalidObject, compareNum, openSuccessModal, openModalMessage, compareString } from '../../../components/TableCustomize'
import { withPermission } from '../../../components/withpermission';
// import SearchForm from './SearchFormDetails';
import AddForm from './AddForm';
import AddForm2 from './AddForm2';
import AddForm3 from './AddForm3';
import { checkResultList } from '../../../utils/global';
import * as CommissioningManagementService from '../../../axios/CommissioningManagement'
import { withRouter } from 'react-router';
// const CreateButton = withPermission(Button, 'create')
const { confirm } = Modal

class CommissioningManagement_details extends Component {
	state = {
		dataSource: [],
		visible: false,
		advanced: false,
		searchItem: {},
		pageSize: 10,
		pageNum: 1,
		total: 40,
		columns: [
			{
				title: '序号',
				dataIndex: 'id',
				width: 50,
				align: 'center',
				render: (text, record, index) => `${index + 1}`,
			},

			{
				title: '检验项目编码',
				width: 150,
				// fixed: 'left',
				dataIndex: 'checkItemCode',
				sorter: (a, b) => compareString(a.checkItemCode, b.checkItemCode)
			},
			{
				title: '检验项目名称',
				width: 150,
				// allowEllipsis: true,
				dataIndex: 'checkItemName',
				sorter: (a, b) => compareString(a.checkItemName, b.checkItemName)
			},
			{
				title: '所属表单',
				width: 100,
				dataIndex: 'formProperties',
				// sorter: (a, b) => compareString(a.partName, b.partName)
			},
			{
				title: '第二类别',  // 第二类别所属分类
				width: 100,
				dataIndex: 'checkTypeSecond',
				sorter: (a, b) => compareString(a.checkTypeSecond, b.checkTypeSecond)
			},
			{
				title: '检验项目属性',
				width: 130,
				dataIndex: 'checkItemProperty',
				sorter: (a, b) => compareNum(a.checkItemProperty, b.checkItemProperty),
				render: (text, record, index) => {
					return text == 1 ? '范围' : text == 2 ? '文本' : text == 3 ? '唯一值' : text == 4 ? '复选' : ''
				}
			},
			{
				title: '检验标准',
				width: 300,
				dataIndex: 'checkStandard',
				// sorter: (a, b) => compareNum(a.checkStandardMax, b.checkStandardMax),
				render: (text, record, index) => {
					let str = ``, remark = record.remark ? '(' + record.remark + ')' : ''
					if (record.checkItemProperty == '1') {
						str += record.checkStandardMin ? record.checkStandardMin + ' ~ ' + record.checkStandardMax : ''
					}
					if (record.checkItemProperty == '2') {
						str += record.checkStandardText ? record.checkStandardText : ''
					}
					if (record.checkItemProperty == '3') {
						let arr = []
						if (record.checkStandardOption1) arr.push({ key: 'checkStandardOption1', label: record.checkStandardOption1 })
						if (record.checkStandardOption2) arr.push({ key: 'checkStandardOption2', label: record.checkStandardOption2 })
						if (record.checkStandardOption3) arr.push({ key: 'checkStandardOption3', label: record.checkStandardOption3 })
						if (record.checkStandardOption4) arr.push({ key: 'checkStandardOption4', label: record.checkStandardOption4 })
						if (record.checkStandardOption5) arr.push({ key: 'checkStandardOption5', label: record.checkStandardOption5 })
						return <div>
							<Radio.Group disabled>
								<Row>
									{
										arr.map(item => {
											return <Radio value={item.key}>{item.label}</Radio>
										})
									}
								</Row>
							</Radio.Group>
							{remark}
						</div>
					}
					if (record.checkItemProperty == '4') {
						let arr = []
						if (record.checkStandardOption1) arr.push({ key: 'checkStandardOption1', label: record.checkStandardOption1 })
						if (record.checkStandardOption2) arr.push({ key: 'checkStandardOption2', label: record.checkStandardOption2 })
						if (record.checkStandardOption3) arr.push({ key: 'checkStandardOption3', label: record.checkStandardOption3 })
						if (record.checkStandardOption4) arr.push({ key: 'checkStandardOption4', label: record.checkStandardOption4 })
						if (record.checkStandardOption5) arr.push({ key: 'checkStandardOption5', label: record.checkStandardOption5 })
						return <div>
							<Checkbox.Group disabled>
								<Row>
									{
										arr.map(item => {
											return <Checkbox value={item.key}>{item.label}</Checkbox>
										})
									}
								</Row>
							</Checkbox.Group>
							{remark}
						</div>
					}
					return str + remark
				}
			},
			{
				title: '检验参数',
				width: 200,
				dataIndex: 'checkParameter',
				editable: true,
				// sorter: (a, b) => compareNum(a.checkParameter, b.checkParameter),
			},
			{
				title: '创建人',
				width: 100,
				dataIndex: 'userName',
				sorter: (a, b) => compareNum(a.userName, b.userName),
			},
			{
				title: '创建时间',
				width: 150,
				dataIndex: 'updateTime',
				ellipsis: true,
				sorter: (a, b) => compareNum(a.updateTime, b.updateTime),
			},
			{
				title: '结果',
				width: 100,
				dataIndex: 'checkResult',
				fixed: 'right',
				sorter: (a, b) => compareNum(a.checkResult, b.checkResult),
				render: (text) => {
					let a = checkResultList.find(item => item.id == text)
					return a.id == '0' ? <Badge color='#1890ff' text={<span style={{ color: '#1890ff' }}>{a.value}</span>} />
						: a.id == '1' ? <Badge status="success" text={<span style={{ color: '#1e8e3e' }}>{a.value}</span>} />
							: a.id == '2' ? <Badge status="error" text={<span style={{ color: '#f00' }}>{a.value}</span>} />
								: a.value
				}
			},
			{
				title: '操作',
				width: 100,
				fixed: 'right',
				dataIndex: 'opts',
				render: (text, record) => <><a onClick={() => this.updateReport(record)}>变更</a></>
			},
			{ dataIndex: '' }
		],
		selectedRows: [],
		selectedRowKeys: [],
		fileList: [[], [], [], []],
		locationData: {},
		searchItemFather: {},
		loading: false,
		downloadLoading: false,
		editRow: {},
		visible_changeReport: false,
		visiable_AddForm2: false,
		visiable_AddForm3: false,
		btnLoading: false,
	};
	componentDidMount() {
		console.log(this.props.location.data)
		this.setState({ locationData: this.props.location.data ? this.props.location.data.record : JSON.parse(localStorage.getItem('CommissioningManagement_detailsList')), searchItemFather: this.props.location.data ? this.props.location.data.searchItem : JSON.parse(localStorage.getItem('CommissioningManagement_searchItem')) }, this.fetch)
		// this.fetch();
	}
	componentWillUnmount() {
		this.setState = () => {
			return;
		};
	}
	//初始化加载数据
	fetch = (pageNum = 1, pageSize = 100) => {
		this.setState({ loading: true });
		const { locationData, searchItem } = this.state;
		const data = { ...locationData, ...searchItem }
		data.pageNum = pageNum;
		data.pageSize = pageSize;
		console.log(data);
		CommissioningManagementService.findMachineReport(data).then(res => {
			this.setState({ loading: false })
			if (res.data.code !== 200) {
				openModalMessage('warning', res.data.data.msg);
				return;
			}
			this.setState({ dataSource: res.data.data.data, total: res.data.data.total, pageNum, pageSize });
		}).catch(err => {
			openModalMessage('error', err.message);
		})
	}


	handleSearch = value => {
		this.setState({ searchItem: value }, this.fetch);
	};

	onHandleAdvanced = () => {
		this.setState({ advanced: !this.state.advanced })
	}
	// table行修改数据
	loadData = (value, dataSource) => {
		this.save(0, value)
		// this.setState({ editRow: value }, this.save)
	}
	// 点击变更
	updateReport = (record) => {
		this.setState({ editRow: record, visiable_AddForm2: true })
	}
	// 提交变更   变更检验数据
	submit_updateReport = () => {
		const { editRow } = this.state
		this.formAdd2.validateFields((err, value) => {
			if (err) return;
			this.setState({ btnLoading: true });
			// console.log(value, 'submit_updateReport')
			// console.log(editRow, 'editRow')
			this.save(0, { ...value, checkItemProperty: editRow.checkItemProperty })
		})
	}
	// 点击结果修正
	chechResult = (record) => {
		const { selectedRows } = this.state
		if (!selectedRows || !selectedRows.length) {
			openModalMessage('warning', '请选择要修改的项目！');
			return;
		}
		this.setState({ visiable_AddForm3: true })
	}
	// 提交结果修正
	submit_checkResult = () => {
		this.formAdd3.validateFields((err, value) => {
			if (err) return;
			this.setState({ btnLoading: true });
			// console.log(value, 'submit_checkResult')
			this.save(1, value)
		})
	}
	// 变更/批量修改
	save = (type, data) => {
		let arr = []
		// 编辑行保存
		if (type == 0) {
			let checkParameter = data.checkParameter
			if (data.checkItemProperty == 4 && data.checkParameter) {
				checkParameter = data.checkParameter.join(',')
			}
			let obj = {
				"checkParameter": checkParameter,
				"checkResult": data.checkResult,
				"machineDetailsId": data.machineDetailsId,
				"userId": localStorage.getItem('userId')
			}
			arr.push(obj)
		}
		// 批量保存
		if (type == 1) {
			const { selectedRows } = this.state
			console.log(data, selectedRows, 'submit_checkResult')
			for (let i in selectedRows) {
				let obj = {
					"checkParameter": selectedRows[i].checkParameter,
					"checkResult": data.checkResult,
					"machineDetailsId": selectedRows[i].machineDetailsId,
					"userId": localStorage.getItem('userId')
				}
				arr.push(obj)
			}
		}

		CommissioningManagementService.updateMachineReport(arr).then(res => {
			console.log(res)
			this.setState({ btnLoading: false })
			if (res.data.code !== 200) {
				openModalMessage('warning', res.data.msg);
				return;
			}
			openSuccessModal(res.data.msg);
			this.fetch()
			this.handleCancel()
		}).catch(err => {
			openModalMessage('error', err.message);
		})
	}

	downloadFather = () => {
		const { dataSource } = this.state;
		this.setState({ downloadLoading: true });
		CommissioningManagementService.exportTestManageDetailExcel({ dtoList: dataSource }).then(res => {
			//设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
			let url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
			// 创建A标签
			let link = document.createElement('a')
			link.style.display = 'none'
			link.href = url
			// 设置的下载文件文件名
			const fileName = decodeURI('试机详情');
			// 触发点击方法
			link.setAttribute('download', fileName)
			document.body.appendChild(link)
			link.click()
			this.setState({ downloadLoading: false })
		})

	}

	resetForm = () => {
		this.formSearch && this.formSearch.resetFields();
		this.setState({ searchItem: {} }, this.fetch);
	}

	// 更换报告模板
	changeReport = () => {
		// const { selectedRows } = this.state
		// if (!selectedRows || !selectedRows.length) {
		// 	openModalMessage('warning', '请选择要变更的项目！');
		// 	return;
		// }
		this.setState({ visible_changeReport: true })
	}
	// 提交 更换报告模板
	submit_ChangeReport = () => {
		this.formAdd.validateFields((err, value) => {
			if (err) return;
			this.setState({ btnLoading: true });
			console.log(value, 'submit_ChangeReport')
			let obj = {
				"fromCode": value.fromCode.key,
				"fromName": value.fromName.label,
				"fromType": value.fromType.key,
				"testMachineId": value.testMachineId,
				"userId": localStorage.getItem('userId')
			}
			let _this = this
			confirm({
				title: '谨慎操作',
				content: '更换模板后，当前的检验数据及进度会丢失，是否继续执行？',
				icon: 'exclamation-circle',
				centered: true,
				okText: '取消',
				cancelText: '确认执行',
				onOk() {
					_this.handleCancel()
				},
				onCancel() {
					CommissioningManagementService.updateMachineTemplate(obj).then(res => {
						_this.setState({ btnLoading: false })
						if (res.data.code !== 200) {
							openModalMessage('warning', res.data.msg);
							return;
						}
						openSuccessModal(res.data.msg);
						_this.fetch()
						_this.handleCancel()
					}).catch(err => {
						openModalMessage('error', err.message);
					})
				},
			});
		})
	}


	handleCancel = e => {
		this.formAdd && this.formAdd.resetFields();
		this.formAdd2 && this.formAdd2.resetFields();
		this.formAdd3 && this.formAdd3.resetFields();
		this.setState({
			visible_changeReport: false,
			visiable_AddForm2: false,
			visiable_AddForm3: false,
			selectedRowKeys: [],
			selectedRows: [],
			btnLoading: false
		});
		// this.fetch();
	};
	render() {
		const { selectedRowKeys, selectedRows, btnLoading, visible_changeReport, visiable_AddForm2, visiable_AddForm3, editRow, locationData, loading, dataSource, advanced, columns, pageNum, pageSize, total, searchItemFather, searchItem, downloadLoading } = this.state;

		const rowSelection = {
			type: 'checkbox',
			selectedRowKeys: selectedRowKeys,
			onChange: (selectedRowKeys, selectedRows) => {
				this.setState({
					selectedRows: selectedRows,
					selectedRowKeys: selectedRowKeys,
				})
			},
			onSelectAll: (selected, selectedRows, changeRows) => {
				const keys = [... this.state.selectedRowKeys];
				const rows = [... this.state.selectedRows];
				if (selected) {
					changeRows.forEach(row => {
						if (isInvalidObject(keys.find(key => key === row.machineDetailsId))) {
							keys.push(row.machineDetailsId);
							rows.push(row);
						}
					})
				} else {
					changeRows.forEach(row => {
						keys.splice(keys.indexOf(row.machineDetailsId), 1);
						rows.splice(rows.indexOf(row), 1);
					})
				}
				this.setState({ selectedRows: rows, selectedRowKeys: keys })
			}
		}
		return (
			<div>
				<BasicLayoutSearch>
					<PageHeader
						style={{ padding: '4px 24px' }}
						onBack={() => this.props.history.push({ pathname: '/CommissioningManagement', data: searchItemFather })}
						title={`${locationData.model}试机详情`}>
					</PageHeader>
					{/* <Divider />
					<SearchForm onSearch={this.handleSearch}
						onClick={this.onHandleAdvanced}
						advanced={advanced} searchItem={searchItem}
						resetForm={this.resetForm}
						ref={node => (this.formSearch = node)} /> */}
				</BasicLayoutSearch>
				<BasicLayout buttons={[
					<Button key={1} onClick={this.changeReport} type='primary' icon='sync'>更换报告模板</Button>,
					<Button key={2} onClick={() => this.fetch()} type='primary' icon='redo'>刷新</Button>,
					<Button key={3} onClick={this.chechResult} type='primary' icon='edit'>结果修正</Button>,
					<Button key={4} onClick={this.downloadFather} type='primary' icon='printer'>打印</Button>,
					<Button key={5} onClick={this.downloadFather} loading={downloadLoading} type='primary' icon='download'>导出</Button>
				]} name={`${locationData.model}试机详情`} icon="table">
					<TableCustomize
						columns={columns}
						rowKey={(record) => record.machineDetailsId}
						rowSelection={rowSelection}
						dataSource={dataSource}
						pagination={false}
						loading={loading}
						allowDrafting={true}
						allowEditable={this.loadData}
						rowClassName={(record, index) => {
							return (['editable-row', index % 2 === 0 ? 'editable-row' : 'editable-row12'])
						}}
					/>
					<BasicPagination pageNum={pageNum} pageSize={pageSize} total={total} loadData={this.fetch} />
				</BasicLayout>

				{/* 更换报告模板 */}
				<Modal
					visible={visible_changeReport}
					destroyOnClose
					title={'更换报告模板'}
					onOk={this.submit_ChangeReport}
					onCancel={this.handleCancel}
					okText="确定"
					cancelText="取消"
					width={'50%'}
					maskClosable={false}
					confirmLoading={btnLoading}
				>
					<AddForm
						ref={node => (this.formAdd = node)}
						formData={locationData}
					/>
				</Modal>

				{/* 变更检验数据 */}
				<Modal
					visible={visiable_AddForm2}
					destroyOnClose
					title={'变更检验数据'}
					onOk={this.submit_updateReport}
					onCancel={this.handleCancel}
					okText="确定"
					cancelText="取消"
					width={'50%'}
					maskClosable={false}
					confirmLoading={btnLoading}
				>
					<AddForm2
						ref={node => (this.formAdd2 = node)}
						formData={editRow}
					/>
				</Modal>

				{/* 批量修改检验结果 */}
				<Modal
					visible={visiable_AddForm3}
					destroyOnClose
					title={'批量修改检验结果'}
					onOk={this.submit_checkResult}
					onCancel={this.handleCancel}
					okText="确定"
					cancelText="取消"
					maskClosable={false}
					confirmLoading={btnLoading}
				>
					<AddForm3
						ref={node => (this.formAdd3 = node)}
					/>
				</Modal>
			</div>
		);
	}
}
export default Form.create()(withRouter(CommissioningManagement_details));